package cn.com.oidreams.wechat.robot.util;

import cn.com.oidreams.common.dto.RobotResponse;
import cn.com.oidreams.common.enums.ExceptionCode;
import cn.com.oidreams.common.enums.ICommonEnum;
import cn.com.oidreams.common.utils.EnumUtil;
import cn.com.oidreams.wechat.robot.entity.BaseRequest;
import cn.com.oidreams.wechat.robot.enums.WeXinTalkEnum;
import cn.com.oidreams.wechat.robot.service.interfaces.IRobot;
import cn.hutool.json.JSONUtil;

import java.util.Map;

/***
 ** @category 请用一句话描述这个类的用途
 ** @author qing.yunhui
 ** @email: qingyh@glodon.com
 ** @createTime: 2021-12-14 19:13
 **/
public class WeXinTalkUtil {

    /**
     * <p>发送钉钉消息</p>
     * @param jsonParams 待发送的消息
     * @param robot 机器人(代发消息的机器人)
     * @return
     * */
    public static RobotResponse sendMessage(String jsonParams, IRobot robot){
        BaseRequest request = JSONUtil.toBean(jsonParams,BaseRequest.class);
        if(null==request){return new RobotResponse(ExceptionCode.MISSING_PARAMETERS);}
        WeXinTalkEnum.MSG_TYPE msgTypeEnum = EnumUtil.getEnumByCode(WeXinTalkEnum.MSG_TYPE.class,request.getMsgtype());
        if(null==msgTypeEnum){return new RobotResponse(ExceptionCode.VERIFICATION_FAILED);}
        return sendMessage(JSONUtil.toBean(jsonParams,msgTypeEnum.getRequest()),robot);
    }
    /**
     * <p>发送钉钉消息</p>
     * @param paramsMap 待发送的消息
     * @param robot 机器人(代发消息的机器人)
     * @return
     * */
    public static RobotResponse sendMessage(Map<String,Object> paramsMap, IRobot robot){
        return sendMessage(JSONUtil.toJsonStr(paramsMap),robot);
    }
    /**
     * <p>发送钉钉消息</p>
     * @param request 待发送的请求消息
     * @param robot 机器人(代发消息的机器人)
     * @return
     * */
    public static RobotResponse sendMessage(BaseRequest request, IRobot robot){
        if(null==request){return new RobotResponse(ExceptionCode.MISSING_PARAMETERS);}
        WeXinTalkEnum.MSG_TYPE MSG_TYPE_ENUM = EnumUtil.getEnumByCode(WeXinTalkEnum.MSG_TYPE.class,request.getMsgtype());
        if(null==MSG_TYPE_ENUM || null==robot){
            return new RobotResponse(ExceptionCode.VERIFICATION_FAILED);
        }
        String robotClassName = robot.getClass().getName();
        if(!(robot instanceof Enum)){
            return new RobotResponse(ExceptionCode.VERIFICATION_FAILED.getCode(),String.format("IRobot实现类[%s]必须是个枚举类!",robotClassName));
        }
        if(!ICommonEnum.class.isAssignableFrom(robot.getClass())){
            return new RobotResponse(ExceptionCode.VERIFICATION_FAILED.getCode(),String.format("IRobot实现类[%s]必须实现ICommonEnum接口!",robotClassName));
        }
        try {
            return MSG_TYPE_ENUM.getService().newInstance().doHandle(request,robot);
        } catch (Exception e) {
            e.printStackTrace();
            return new RobotResponse(ExceptionCode.SYSTEM_ERROR.getCode(),e.getMessage());
        }
    }

}
